package scala.for_the.impatient

import java.io.FileReader
import java.util.Properties

import scala.collection.mutable.ArrayBuffer

/**
  * Created by shichen on 2017/5/24.
  */

class Counter {  //类不声明为public，公有可见
  private var value = 0
  private[this] var value2 = 0 //不能通过other.value2访问
  def incre()  { value += 1} //方法默认公有
  def cur = value

  def lessThan(other: Counter) = value < other.value

}

class Person {
  var privateAge = 0 //default public
  val ts = new java.util.Date
  def age = privateAge //getter
  def age_=(newValue:Int): Unit = { //setter
    if (newValue > privateAge) privateAge = newValue
  }
}

//在前面的类名后数字的类实际上表示书中的同一个类，方便介绍不同的部分
class Person2 { //类如果没有显式定义主构造器，自动拥有一个无参主构造器
  private var name = ""
  private var age = 0

  def this(name:String) { //辅助构造器
    this() //调用主构造器
    this.name = name
  }

  def this (name:String, age:Int) {
    this(name) //调用前一个辅助构造器
    this.age = age
  }
}

class Person3(name: String, val age: Int) { //不带val/var的参数至少被一个方法使用，就升为字段
  println("another person:") //这是主构造器的一部分，有对象构造就会被执行
  def desc = name + " is " + age + " years old"
}

class MyProg {
  private val props = new Properties() //构造器仅仅简单执行类体中所有语句
  props.load(new FileReader("my.conf"))
  println("done")
}

//nested class
class Network {
  class Member(val name:String) {
    val contacts = new ArrayBuffer[Member]()
  }

  private val members = new ArrayBuffer[Member]()

  def join(name:String) = {
    val m = new Member(name)
    members += m
    m
  }
}

object ch05 {
  def main(args: Array[String]): Unit = {
    t_basics()
  }

  def t_basics(): Unit = {
    var fred = new Person
    fred.age = 30
    fred.age = 21
    println(fred.age)
    println(fred.ts)

    val my = new Counter
    my.incre()
    my.incre()
    println(my.cur)

    printAny("hello") //hello
    printUnit("hello") //()

    t_ctor()
  }

  def t_ctor(): Unit = {
    val p1 = new Person2 //main ctor
    val p2 = new Person2("cs") //1th sub ctor
    val p3 = new Person2("cs",27) //2nd sub ctor
  }

  def printAny(x:Any): Unit = {
    println(x)
  }
  def printUnit(x: Unit): Unit = {
    println(x)
  }
}